package com.mtnz.njk.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.mtnz.njk.Util.TokenNote;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 自定义的拦截器
 *
 * @author onegis
 */
public class AuthenticationInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
            throws Exception {

        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        //检查有没有需要用户权限的注解 @TokenNote
        if (method.isAnnotationPresent(TokenNote.class)) {
            TokenNote userLoginToken = method.getAnnotation(TokenNote.class);
            if (userLoginToken.required()) {
                //开始认证
                if (token == null) {
                    throw new RuntimeException("没有token，生成token！");
                }
                //拿到token中的phone
                String phone;
                try {
                    phone = JWT.decode(token).getAudience().get(0);
                } catch (Exception e) {
                    throw new RuntimeException("401");
                }

                //验证token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(phone)).build();
                try {
                    jwtVerifier.verify(token);
                } catch (Exception e) {
                    throw new RuntimeException("401");
                }

                return true;
            }

        }

        return true;
    }

}

